package repo

import (
	"app-box/models"
	"app-box/models/result"
	"app-box/models/tables"

	"gorm.io/gorm"
)

type AppBoxRepo struct {
	BaseRepo
}

func NewAppBoxRepo(DB *gorm.DB) *AppBoxRepo {
	var repo = new(AppBoxRepo)
	repo.DB = DB
	return repo
}

func (repo *AppBoxRepo) Insert(app *tables.App) error {
	return repo.DB.Create(app).Error
}

func (repo *AppBoxRepo) GetAppByID(id models.IDType, app *tables.App) error {
	return repo.DB.First(app, "id = ?", id).Error
}

func (repo *AppBoxRepo) GetAppListByUserID(userID models.IDType, list *[]result.AppList) error {
	return repo.DB.Raw(`select * from (
		select * from apps where user_id = ? order by created_at desc
		) group by package_name, platform`, userID).Scan(list).Error
}

func (repo *AppBoxRepo) GetAppListByPackageName(userID models.IDType, platform, packageName string, list *[]result.AppList) error {
	return repo.DB.Raw(`select * from apps where  user_id = ? and platform = ? and package_name = ? order by created_at desc`, userID, platform, packageName).Scan(list).Error
}

func (repo *AppBoxRepo) GetAppBox(userid models.IDType, platform, packageName string, appBox *tables.AppBox) error {
	return repo.DB.Model(appBox).Where("user_id = ? AND platform = ? AND package_name = ?", userid, platform, packageName).First(appBox).Error
}

func (repo *AppBoxRepo) GetAppBoxByID(id models.IDType, appBox *tables.AppBox) error {
	return repo.DB.Model(appBox).Where("id = ?", id).First(appBox).Error
}

func (repo *AppBoxRepo) GetAppBoxByCustomID(id string, appBox *tables.AppBox) error {
	return repo.DB.Model(appBox).Where("custom_id = ?", id).First(appBox).Error
}

func (repo *AppBoxRepo) UpdateAppBoxPassword(id models.IDType, password string) error {
	return repo.DB.Model(tables.AppBox{}).Where("id = ?", id).Update("password", password).Error
}

func (repo *AppBoxRepo) UpdateAppBoxDescription(id models.IDType, description string) error {
	return repo.DB.Model(tables.AppBox{}).Where("id = ?", id).Update("description", description).Error
}

func (repo *AppBoxRepo) UpdateAppBoxCustomID(id models.IDType, CustomID string) error {
	return repo.DB.Model(tables.AppBox{}).Where("id = ?", id).Update("custom_id", CustomID).Error
}
